<?php

namespace app\admin\controller\vppz;

use app\common\controller\Backend;

use app\admin\model\Admin as AdminModel;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class AreaAdmin extends Base
{

    /**
     * AreaAdmin模型对象
     * @var \app\admin\model\vppz\AreaAdmin
     */
    protected $model = null;

	protected $searchFields = ['id','admin.username','admin.nickname'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\vppz\AreaAdmin;

		// 给数据附加当前appid，appid由Base负责解析
		$this->model::event('before_insert', function ($row){
			$row->app_id=$this->app_id;
		});
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
			
			$area_id = input('area_id');

            $list = $this->model
                    ->with(['admin','area'])
                    ->where($where)->where('area_id',$area_id)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                
                $row->getRelation('admin')->visible(['username','nickname','avatar']);
				$row->getRelation('area')->visible(['name']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
		
		// 当前区域注入到JS中
		$ids = input('ids');
		$this->assignconfig('area_id',$ids);

        return $this->view->fetch();
    }


	public function add()
   {
		$area_id = input('area_id');
		
		$username = input('username');

		$AdminModel = new AdminModel;
		$admin = $AdminModel->where(['username'=>$username])->find();
		if(empty($admin)){
			$this->error('该管理员账号不存在');
		}
		
		$aa = $this->model->where(['app_id'=>$this->app_id,'area_id'=>$area_id,'admin_id'=>$admin['id']])->find();
		if(!empty($aa)){
			$this->error('该账号已是该区域管理员，请勿重复添加');
		}

		$aa = [
			'area_id'=>$area_id,
			'admin_id'=>$admin['id']
		];
		
		$ret=$this->model->save($aa);
		$aa['id'] = $this->model->id;
		if(empty($ret) || empty($aa['id'])){
			$this->error('添加失败，请重试');
		}


		$this->success($area_id."保存成功".$username);
	}
}
